package com.feng.vhr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.feng.vhr.auth.MyAuthenticationEntryPoint;
import com.feng.vhr.auth.MyFailedHandler;
import com.feng.vhr.auth.MyPasswordEncoder;
import com.feng.vhr.auth.MySuccessHandler;
import com.feng.vhr.common.RespBean;
import com.feng.vhr.service.impl.HrServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MySuccessHandler mySuccessHandler;

    @Autowired
    private HrServiceImpl hrService;

    @Autowired
    private MyFailedHandler myFailedHandler;

    @Autowired
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;


    @Bean
    PasswordEncoder passwordEncoder() {
        return new MyPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hrService).passwordEncoder(passwordEncoder());
    }

    @Bean
    SessionRegistryImpl sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    MyLoginFilter loginFilter() throws Exception {
        MyLoginFilter loginFilter = new MyLoginFilter();
        loginFilter.setAuthenticationSuccessHandler(mySuccessHandler
        );
        loginFilter.setAuthenticationFailureHandler(
                myFailedHandler
        );
        loginFilter.setAuthenticationManager(authenticationManagerBean());
        loginFilter.setFilterProcessesUrl("/doLogin");
        ConcurrentSessionControlAuthenticationStrategy sessionStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
        sessionStrategy.setMaximumSessions(1);
        loginFilter.setSessionAuthenticationStrategy(sessionStrategy);
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
        http
                .logout()//退出登录
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {//退出登录成功的处理器
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset=utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功")));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/verifyCode").permitAll() //设置那些路径不需要认证，可以直接访问
//                .antMatchers("/system/config/menu","/hr/info").permitAll()
                .antMatchers("/chat/**","/ws/chat","/system/config/menu","/hr/**").hasAnyRole("manager","personnel","recruiter","train","performance","admin")
                .antMatchers("/employee/basic/**").hasAnyRole("manager","personnel","performance","admin")
                .antMatchers("/salary/**").hasAnyRole("manager","performance","admin")
                .antMatchers("/system/basic/**").hasAnyRole("manager","admin")
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(myAuthenticationEntryPoint);
    }
}
